package com.chinda.common.mybatis;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chinda.common.constants.CommonConstant;
import com.chinda.common.security.SysUserDetails;
import com.chinda.common.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 属性填充器
 * @author Wang Chinda
 * @date 2021/6/6
 */
@Slf4j
@Component
public class AutoMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert populate...");
        String username;
        try {
            SysUserDetails userDetail = SecurityUtil.getUserDetail();
            username = userDetail.getUsername();
        } catch (Exception e) {
            username = CommonConstant.ANONYMOUS;
        }
        String finalUsername = username;
        this.strictInsertFill(metaObject, "createBy", () -> finalUsername, String.class);
        this.strictInsertFill(metaObject, "createDate", DateTime::new, Date.class);
        this.strictInsertFill(metaObject, "modifyBy", () -> finalUsername, String.class);
        this.strictInsertFill(metaObject, "modifyDate", DateTime::new, Date.class);
        this.strictInsertFill(metaObject, "del", () -> 0, Integer.class);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update populate...");
        SysUserDetails userDetail = SecurityUtil.getUserDetail();
        String username = userDetail.getUsername();
        this.strictUpdateFill(metaObject, "modifyBy", () -> username, String.class);
        this.strictUpdateFill(metaObject, "modifyDate", DateTime::new, Date.class);
    }
}
